<template>
  <view>
    <view class="form-container fixed-form-container">
      <uni-forms ref="form" :modelValue="formData" :rules="rules" labelPosition="top">
        <view class="hidden-title">项目基础信息</view>
        <cu-cell-group>
          <uni-forms-item v-if="formData.projectCode" name="projectCode">
            <cu-cell title="项目编号" :description="formData.projectCode"> </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="projectName">
            <cu-cell v-if="formData.projectCode" title="作业项目名称" :description="formData.projectName"> </cu-cell>
            <cu-cell v-else title="作业项目名称" column required>
              <u--textarea
                v-model="formData.projectName"
                placeholder="请使用具有辨识度的文字命名，便于后续查阅（限30字）"
                autoHeight
                maxlength="30"
              ></u--textarea>
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="projectTypeId">
            <cu-cell class="cu-cell--select-v2" title="项目类型" required>
              <CuSelectV2
                v-model="formData.projectTypeId"
                title="项目类型"
                placeholder="请选择项目类型"
                label-key="title"
                value-key="typeId"
                :options="projectTypeOptions"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="projectDate">
            <cu-cell class="cu-cell--select-v2" title="项目日期">
              <CuSelectV2
                v-model="formData.projectDate"
                title="项目日期"
                placeholder="请选择项目日期"
                label-key="label"
                value-key="label"
                :options="projectDateOptions"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="areaId">
            <cu-cell v-if="formData.projectCode" title="所属区域" :description="formData.areaName"> </cu-cell>
            <cu-cell
              v-else
              title="所属区域"
              link
              required
              :description="formData.areaName"
              placeholder="请选择所属区域"
              @click="showFactoryPicker"
            >
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item :key="formData.directorId || 0" name="directorId">
            <cu-cell
              title="项目负责人"
              required
              link
              placeholder="请选择项目负责人"
              :description="formData.directorName"
              @click="showUserSelector('director')"
            ></cu-cell>
          </uni-forms-item>
          <template v-if="formData.directorId">
            <uni-forms-item>
              <cu-cell title="项目负责部门" :description="formData.deptName"></cu-cell>
            </uni-forms-item>
            <uni-forms-item>
              <cu-cell title="项目负责岗位" :description="formData.postName"></cu-cell>
            </uni-forms-item>
          </template>
          <uni-forms-item name="guardianId">
            <cu-cell
              title="监护人"
              required
              link
              placeholder="请选择监护人"
              :description="formData.guardianName"
              @click="showUserSelector('guardian')"
            ></cu-cell>
          </uni-forms-item>
          <view style="font-size: 12px; color: #999; padding: 4px 0">该人员需录入监护人证书</view>
          <uni-forms-item name="description">
            <cu-cell title="项目描述" column required>
              <u--textarea
                v-model="formData.description"
                placeholder="简要描述作业项目（限50字）"
                autoHeight
                maxlength="50"
              ></u--textarea>
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="judgmentUser">
            <cu-cell
              title="现场研判人员"
              link
              placeholder="请选择现场研判人员"
              :description="judgmentUserName"
              @click="showUserSelector('judgment')"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="judgmentPhotos">
            <cu-cell title="现场研判照片(限3张)" column>
              <image-upload :imageUrl="formData.judgmentPhotos" state="edit" :limit="3" @change="imageChange" />
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>
        <view class="hidden-title">作业项目详情(必填)</view>
        <cu-cell-group>
          <cu-cell title="作业类型和级别">
            <view class="text-right" @click="handleAddTicket()">添加</view>
          </cu-cell>
        </cu-cell-group>
        <view style="background: #f3f4f8; padding-left: 12px">
          <view class="cu-card-wrap" v-for="(item, index) in tickets" :key="item.workId">
            <view class="affix">
              <image
                class="affix-icon"
                :src="`/static/images/ticket-type/work-type-${item.workTypeFlag}.png`"
                mode="aspectFit"
              />
            </view>
            <view class="body-wrap">
              <view class="content-wrap">
                <view class="label">作业类型：</view>
                <view class="value">
                  {{ item.workTypeLabel }} {{ `${item.levelLabel}` ? `（${item.levelLabel}）` : '' }}</view
                >
              </view>
              <view class="content-wrap">
                <view class="label">作业点：</view>
                <view class="value">{{ item.operationPoint }}</view>
              </view>
              <view class="content-wrap">
                <view class="label">作业区域：</view>
                <view class="value">{{ item.areaName }}</view>
              </view>
              <view class="content-wrap">
                <view class="label">作业内容：</view>
                <view class="value">{{ item.workContent }}</view>
              </view>
              <view class="content-wrap">
                <view class="label">作业单位：</view>
                <view class="value">{{ item.unitName }}</view>
              </view>
              <view class="content-wrap">
                <view class="label">作业单位负责人：</view>
                <view class="value">{{ item.directorName }}</view>
              </view>
              <view class="content-wrap">
                <view class="label">风险辨识结果：</view>
                <view class="value">{{ item.riskIdentificationResult }}</view>
              </view>
            </view>
            <view class="footer-wrap">
              <view class="button-wrap button-wrap-todo">
                <view class="button-wrap-left"> </view>
                <view class="flex">
                  <view class="button" @click="handleEditTicket(item, index)">修改</view>
                  <view class="button" @click="handleRemoveTicket(item)">删除</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="hidden-title">风险等级</view>
        <cu-cell-group>
          <uni-forms-item name="riskIdentificationResult">
            <cu-cell class="cu-cell--select-v2" title="风险等级" required>
              <CuSelectV2
                v-model="formData.riskIdentificationResult"
                title="风险等级"
                placeholder="请选择风险等级"
                label-key="label"
                value-key="value"
                :options="riskIdentificationResultOptions"
              />
            </cu-cell>
          </uni-forms-item>
          <view style="font-size: 12px; color: #999; padding: 4px 0"
            >涉及到三种及以上特殊作业的为较大风险，涉及到一到两种特殊作业的为一般风险</view
          >
        </cu-cell-group>
      </uni-forms>
    </view>

    <view class="submit-group">
      <button class="u-button block" :ripple="true" @click="handleSubmit">上报</button>
    </view>

    <cu-tree-select
      ref="areaSelectRef"
      :checkList="areaCheckList"
      :request-api="getFactoryArea"
      label-key="areaName"
      value-key="areaId"
      children-key="childList"
      @change="onAreaChange"
    />

    <!-- 常规用户选择器 -->
    <cu-dept-user-select
      ref="deptUserSelectRef"
      :userRequestApi="deptUserSelectProps.userRequestApi"
      :checkList="deptUserSelectProps.checkList"
      :multiple="deptUserSelectProps.userSelectorMultiple"
      :with-count="deptUserSelectProps.withCount"
      @change="onDeptUserChange"
    ></cu-dept-user-select>
  </view>
</template>
<script>
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuSelectV2 from '@/components/cu-select-v2/cu-select-v2.vue'
import { createWorkProject, getFactoryArea, queryProjectGuardian, queryWorkProjectType } from '@/api/spw/project'
import CuTreeSelect from '@/components/cu-tree-select/cu-tree-select.vue'
import CuDeptUserSelect from '@/components/cu-dept-user-select/cu-dept-user-select.vue'
import ImageUpload from '@/components/image-upload/index.vue'
import dayjs from 'dayjs'
export default {
  components: { ImageUpload, CuDeptUserSelect, CuTreeSelect, CuSelectV2, CuCell, CuCellGroup },
  data() {
    return {
      riskIdentificationResultOptions: [
        { label: '一般风险', value: '一般风险' },
        { label: '较大风险', value: '较大风险' }
      ],
      tickets: [],
      loading: false,
      formData: {
        projectCode: '',
        projectName: '',
        projectTypeId: '',
        areaId: '',
        areaName: '',
        directorId: '',
        directorName: '',
        deptId: '',
        deptName: '',
        postId: '',
        postName: '',
        guardianId: '',
        guardianName: '',
        judgmentUser: [],
        judgmentUserIds: '',
        description: '',
        judgmentPhotos: '',
        riskIdentificationResult: '',
        projectDate: dayjs().add(1, 'day').format('YYYY-MM-DD')
      },
      areaCheckList: [],
      projectTypeOptions: [],
      projectDateOptions: [
        {
          label: dayjs().format('YYYY-MM-DD')
        },
        {
          label: dayjs().add(1, 'day').format('YYYY-MM-DD')
        }
      ],
      deptUserSelectProps: {
        checkList: [],
        userRequestApi: null,
        userSelectorMultiple: false,
        withCount: true
      },
      rules: {
        projectName: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        projectTypeId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        areaId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        directorId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        guardianId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        description: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        projectDate: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        projectCode: {
          rules: [
            {
              required: false
            }
          ]
        }
      }
    }
  },
  computed: {
    judgmentUserName() {
      const len = this.formData.judgmentUser.length
      if (!len) {
        return ''
      }
      const desc = []
      const max = len > 2 ? 2 : len
      for (let i = 0; i < max; i++) {
        desc.push(this.formData.judgmentUser[i].name)
      }
      const descStr = len > 2 ? desc.join('、') + `等${len}人` : desc.join('、')
      return descStr
    }
  },
  onBackPress(options) {
    if (options.from === 'backbutton') {
      this.$modal.confirm('填写的内容不会保存，是否返回？').then(() => {
        uni.navigateBack()
      })
      return true
    }
  },
  onLoad() {
    queryWorkProjectType().then((res) => {
      this.projectTypeOptions = res.data ?? []
    })
  },
  // 筛选按钮点击
  onNavigationBarButtonTap(e) {
    uni.navigateTo({
      url: `/pages/jobSlip/project/import`,
      events: {
        'project-ticket:import:success': (data) => {
          this.formData.projectCode = data.projectCode
          this.formData.projectId = data.projectId
          this.formData.projectName = data.projectName
          this.formData.projectTypeId = data.projectTypeId
          this.formData.areaId = data.areaId
          this.formData.areaName = data.areaName
          this.formData.directorId = data.directorId
          this.formData.directorName = data.directorName
          this.formData.deptId = data.deptId
          this.formData.deptName = data.deptName
          this.formData.postId = data.postId
          this.formData.postName = data.postName
          this.formData.guardianId = data.guardianId
          this.formData.guardianName = data.guardianName
          this.formData.description = data.description
        }
      }
    })
  },
  methods: {
    getFactoryArea,
    handleAddTicket() {
      uni.navigateTo({
        url: `/pages/jobSlip/work-ticket/new-ticket`,
        events: {
          'project-ticket:form:success': (data) => {
            console.log('handleAddTicket', data)
            this.tickets.push({
              ...data,
              workId: Date.now().toString()
            })
            if (this.tickets.length > 2) {
              this.formData.riskIdentificationResult = this.riskIdentificationResultOptions[1].value
            } else {
              this.formData.riskIdentificationResult = this.riskIdentificationResultOptions[0].value
            }
          }
        }
      })
    },
    handleEditTicket(item, index) {
      this.ticketIndex = index
      uni.navigateTo({
        url: `/pages/jobSlip/work-ticket/new-ticket`,
        events: {
          'project-ticket:form:success': (data) => {
            console.log('handleEditTicket', data)
            this.$set(this.tickets, this.ticketIndex, {
              ...data
            })
          }
        },
        success: (res) => {
          res.eventChannel.emit('project-ticket:form', { data: JSON.parse(JSON.stringify(item)) })
        }
      })
    },
    handleRemoveTicket(index) {
      uni.showModal({
        title: '提示',
        content: '是否删除当前作业类型？',
        showCancel: true,
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            this.tickets.splice(index, 1)
            if (this.tickets.length > 2) {
              this.formData.riskIdentificationResult = this.riskIdentificationResultOptions[1].value
            } else {
              this.formData.riskIdentificationResult = this.riskIdentificationResultOptions[0].value
            }
          }
        }
      })
    },
    imageChange(urlList) {
      this.formData.judgmentPhotos = urlList.join(',')
    },
    async handleSubmit() {
      if (this.loading) {
        return
      }
      await this.$refs.form.validate()
      if (this.tickets.length < 1) {
        uni.showToast({
          title: '请添加作业类型',
          icon: 'none'
        })
        return
      }
      // 处理研判人员数据
      let ids = []
      if (this.formData.judgmentUser.length)
        this.formData.judgmentUser.forEach((item) => {
          ids.push(item.userId)
        })
      this.formData.judgmentUserIds = ids.join(',')
      this._add()
    },
    async _add() {
      this.loading = true
      uni.showLoading({
        title: '正在上报',
        mask: true
      })
      let data = {
        specialWorkSaveReqList: this.tickets,
        workProjectSaveReq: this.formData,
        judgmentPhotos: this.formData.judgmentPhotos,
        judgmentUserIds: this.formData.judgmentUserIds,
        projectDate: this.formData.projectDate,
        riskIdentificationResult: this.formData.riskIdentificationResult
      }
      await createWorkProject(data).finally(() => {
        uni.hideLoading()
        this.loading = false
      })
      this.$modal.msgSuccess('上报成功')
      setTimeout(() => {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('project:create:success', {
          data: true
        })
        uni.navigateBack()
      }, 1000)
    },
    showFactoryPicker() {
      this.$refs.areaSelectRef.open()
    },
    onAreaChange(val) {
      this.areaCheckList = val
      this.formData.areaId = val[0].areaId
      this.formData.areaName = val[0].areaName
    },
    onGuardianChange(obj) {
      console.log(obj)
      this.formData.guardianId = obj.value
      this.formData.guardianName = obj.name
    },
    showUserSelector(type) {
      this.userSelectorType = type
      this.deptUserSelectProps.userRequestApi = null
      this.deptUserSelectProps.withCount = true
      if (type === 'director') {
        this.deptUserSelectProps.userSelectorMultiple = false
        this.deptUserSelectProps.checkList = [
          {
            userId: this.formData.directorId,
            name: this.formData.directorName,
            deptId: this.formData.deptId,
            deptName: this.formData.deptName,
            postIds: this.formData.postId,
            postNames: this.formData.postName
          }
        ]
      } else if (type === 'judgment') {
        this.deptUserSelectProps.userSelectorMultiple = true
        this.deptUserSelectProps.checkList = this.formData.judgmentUser
      } else if (type === 'guardian') {
        this.deptUserSelectProps.userSelectorMultiple = false
        this.deptUserSelectProps.withCount = false
        this.deptUserSelectProps.checkList = [
          {
            userId: this.formData.guardianId,
            name: this.formData.guardianName
          }
        ]
        this.deptUserSelectProps.userRequestApi = queryProjectGuardian
      }
      this.$refs.deptUserSelectRef.open()
    },
    onDeptUserChange(val) {
      if (this.userSelectorType === 'director') {
        this.formData.directorId = val[0].userId
        this.formData.directorName = val[0].name
        this.formData.deptId = val[0].deptId ?? ''
        this.formData.deptName = val[0].deptName ?? ''
        this.formData.postId = val[0].postIds ? val[0].postIds.split(',')[0] : ''
        this.formData.postName = val[0].postNames ? val[0].postNames.split(',')[0] : ''
      } else if (this.userSelectorType === 'judgment') {
        this.formData.judgmentUser = val
      } else if (this.userSelectorType === 'guardian') {
        this.formData.guardianId = val[0].userId
        this.formData.guardianName = val[0].name
      }
    }
  }
}
</script>

<style scoped lang="scss">
.button-wrap {
  padding: 20px 30px;

  .submit-button {
    background: #454a5e;
    line-height: 88rpx;
    text-align: center;
    border-radius: 50rpx;
    font-size: 36rpx;
    color: #fff;
  }
}

.cu-card-wrap {
  //margin-bottom: 24rpx;
  position: relative;
  margin: 0;
  padding: 10px;
  margin-top: 12px;
  margin-right: 12px;
  border: 1px solid #eaeef1;
}

.affix {
  //width: 90px;
  height: 30px;
  position: absolute;
  top: 0;
  right: 0;
}

uni-image.affix-icon {
  height: 30px !important;
  width: 78px !important;
}

.button-wrap.button-wrap-todo {
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 20rpx;
  .button-wrap-left {
    display: flex;
    align-items: center;

    > view {
      margin-right: 16rpx;
      margin-left: 0;
    }
  }
}
</style>
